﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.presentation.nodeFactory;
using umbraco.presentation;
using System.Xml;

namespace Umb.SimpleWebsite.Shared.Content
{
    public class Site
    {
        private Node data;
        public Node Data {
            get {
                if (data == null)
                {
                    XmlAttribute aid= UmbracoContext.Current.GetXml().SelectSingleNode("/*/@id") as XmlAttribute;
                    data= new Node(int.Parse(aid.Value));
                    return data;
                }
                return data;
            }
            set { data = value; } 
        }
        public virtual String GetProperty(string name, bool isMandatory)
        {

            if (Data == null) return "null data";
            if (isMandatory)
            {
                return Data.GetProperty(name).Value;
            }
            else
            {
                Property p = Data.GetProperty(name);
                return p == null ? null : p.Value;
            }
        }


        public Site(Node siteNode)
        {
            Data = siteNode;
        }


        public int Id { get { return Data.Id;} }
        public string Title { get { return GetProperty("title", true); } }

        public string Logo { get { return GetProperty("siteLogo",false); } }

        public string Url { get { return Data.NiceUrl; } }

        public string HomePage { get { return GetProperty("homepage", false); } }
        public Node HomePageNode { get {
            Property p = Data.GetProperty("homepage");
            return p == null || string.IsNullOrEmpty(p.Value) 
                ? null 
                : new Node(int.Parse(p.Value));
        } }

        private Node root;
        public Node Root
        {
            get {
                if (root == null)
                {
                    //cache??  :) by site node we could get root from cache

                    //get data from site default page
                    Node hn = HomePageNode;
                    if (hn != null)
                    {
                        Node result=hn;
                        while (result != null)
                            if (result.NodeTypeAlias.Equals("home", StringComparison.InvariantCultureIgnoreCase)) return result;
                            else result = result.Parent;                        
                    }
                    //if not - find first site child
                    foreach (Node result in Data.Children)
                        if (result.NodeTypeAlias.Equals("home", StringComparison.InvariantCultureIgnoreCase)) return result;
                    return null;
                }
                return root;
            }
        }
    }
}
